package com.bwie;

import com.alibaba.fastjson.JSON;
import com.bwie.common.domain.Student;
import com.bwie.common.remote.system.RemoteEsService;
import com.bwie.common.result.Result;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Import;

import java.util.List;

/**
 * @Author：ShenJiaFeng
 * @Package：com.bwie
 * @Project：zg5_19
 * @name：EsApplication
 * @Date：2024/2/18 8:54
 */
//排除数据源
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
//开启定时器
//@EnableScheduling
//@Import注解来导入RemoteEsService类 用来导入指定的配置类或者Bean
@Import(value = {RemoteEsService.class})
@EnableFeignClients(basePackages = {"com.bwie"})
public class EsApplication implements ApplicationRunner {
    private final RemoteEsService remoteEsService;
    private final RestHighLevelClient client;

    public EsApplication(RemoteEsService remoteEsService, RestHighLevelClient client) {
        this.remoteEsService = remoteEsService;
        this.client = client;
    }

    public static void main(String[] args) {
        SpringApplication.run(EsApplication.class);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest("student");
        deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());

        try {
            client.deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Result<List<Student>> listResult = remoteEsService.studentLists();
        List<Student> students = listResult.getData();
        BulkRequest bulkRequest = new BulkRequest();
        for (Student student : students) {
            IndexRequest stu = new IndexRequest("student").id(student.getStudentId() + "").source(JSON.toJSONString(student), XContentType.JSON);
            bulkRequest.add(stu);
        }

        try {
            client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
